package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IBoardService boardService;
    @Resource
    private IArticleService articleService;

    @ApiOperation("写文章")
    @PostMapping("/create")
    public AppResult createArticle(HttpServletRequest request,
                                   @ApiParam("板块id") @RequestParam(value = "boardId") @NonNull Long id,
                                   @ApiParam("文章标题") @RequestParam(value = "title") @NonNull String title,
                                   @ApiParam("帖子内容") @RequestParam(value = "content") @NonNull String content){

        //获取session对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if (user.getState() == 1) {
            //返回错误
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }
        //判断板块是否被禁用
        Board board = boardService.selectById(id);
        if (board.getState() == 1) {
            //返回错误
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //都正常，封装文章对象
        Article article = new Article();
        article.setBoardId(id);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        //调用articleService，插入数据库
        articleService.create(article);
        //返回结果
        log.info(user.getUsername() + " 写入帖子成功");
        return AppResult.success();
    }

    /**
     * 根据boardId返回帖子列表
     * @return
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId (@ApiParam("版块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> result;
        if (boardId == null){
            result = articleService.selectAll();
        }else{
            result = articleService.selectAllByBoardId(boardId);
        }
        if (result == null) {
            result = new ArrayList<>();
        }
        return AppResult.success(result);
    }

    /**
     * 根据用户Id获取帖子列表
     * @param userId 版块Id
     * @return 帖子列表
     */
    // API 描述
    @ApiOperation("获取用户发布的所有帖子")
    // 指定接口URL映射
    @GetMapping("/getByUserId")
    public AppResult<List<Article>> getAllByUserId (@ApiParam(value = "用户Id") @RequestParam("userId") @NonNull
                                                            Long userId) {
        // 定义返回结果
        List<Article> result = articleService.selectByUserId(userId);
        // 处理结果为null的情况
        if (result == null) {
            result = new ArrayList<>();
        }
        // 返回结果集
        return AppResult.success(result);
    }

    @ApiOperation("获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> selectDetailById (HttpServletRequest request,
                                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        // 从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用Service，获取帖子详情
        Article article = articleService.selectDetailById(id);
        // 判断结果是否为空
        if (article == null) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if (user.getId() == article.getUserId()) {
            // 标识为作者
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @ApiOperation("编辑帖子")
    @GetMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子正文") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content){
        //获取登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //查询帖子
        Article article = articleService.selectById(id);
        //判断帖子作者是否为登录者
        if (article.getUserId() != user.getId()) {
            log.warn("您无权修改");
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用service层接口进行更新
        articleService.modify(id,content);
        return AppResult.success("更新成功");
    }

    /**
     * 删除帖子
     * @param request
     * @param id
     * @return
     */
    @ApiOperation("根据Id删除帖子")
    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //获取登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //查询帖子
        Article article = articleService.selectById(id);
        //判断帖子作者是否为登录者
        if (article.getUserId() != user.getId()) {
            log.warn("只能删除自己发布的帖子");
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用service层接口进行更新
        articleService.deleteById(id);
        return AppResult.success("删除帖子成功");
    }


}
